<?php

namespace App\Http\Controllers\App;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Models\Order;

class OrderController extends BaseController
{   
    /**
     * 展示订单
     *
     * @return void
     */
    public function show( Request $request )
    {
        $tel        = $request->input('tel');
        $order_sn   = $request->input('order_sn');
        $start_time = $request->input('start_time');
        $end_time   = $request->input('end_time');
        $status     = $request->input('status', null);
        
        $where = [];

        $query = Order::orderBy('id', 'desc');
        if ( $tel ) {
            $where[] = ['user_mobile', 'like', '%'. $tel. '%'];
        }

        if ( $order_sn ) {
            $query->where('order_sn', 'like', '%'. $order_sn. '%');
        }

        if ( $start_time ) {
            $query->whereDate('created_at', '>', $start_time);
        }

        if ( $end_time ) {
            $query->whereDate('created_at', '<', $end_time);
        }

        if ( $status !== null ) {
              switch ($status) {
                case 0:
                    $type = [0];
                    break;

                case 1:
                    $type = [1];
                    break;

                case 2:
                    $type = [2, 3];
                    break;
                
                default:
                    return self::error('请传递正确的状态');
                    break;
            }

            $query->whereIn('status', $type);
        }

        $data = $query->with([
            'user' => function ( $query ) {
                $query->select('user_mobile', 'id');
            }
        ])->whereHas('user', function ( $query ) use ( $where ) {
            $query->where($where);
        })->paginate(15);    
        
        return self::json($data);
    }

    /**
     * 发货
     *
     * @return void
     */
    public function edit( Request $request )
    {
        $id = $request->input('id');

        $info = Order::where('status', 1)->find($id);

        if ( !$info ) {
            return self::error('请传递正确的订单');
        }

        $info->status = 2;
        $info->save();

        return self::success('发货成功');
    }
}
